<template>
  <view class="dishes-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <text class="back-text">返回</text>
        </view>
        <view class="title">
          <text class="title-text">确认采买</text>
        </view>
        <view style="display: flex;align-items: center">
          <view class="save-btn" @click="save(false)" style="margin-right: 32rpx">
            <text class="save-text">保存</text>
          </view>
          <view class="save-btn" @click="submit(true)">
            <text class="save-text" style="color: green">提交</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-box">
        <image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
        <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索菜品名称"
            class="search-input"
            @input="onSearchInput"
        />
      </view>
    </view>

    <!-- 菜品列表 -->
    <scroll-view class="dish-list" scroll-y="true">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="filteredDishList.length === 0" class="empty-state">
        <image src="/static/image/no_permission.png" class="empty-icon" mode="aspectFit"></image>
        <text class="empty-text">暂无菜品</text>
      </view>

      <!-- 菜品列表 -->
      <view v-else class="dish-list-container">
        <view v-for="(dish, index) in filteredDishList" :key="dish.id" class="dish-item">
          <view class="dish-info">
            <view class="dish-name">
              <text class="name-text">{{ dish.dish && dish.dish.name }}</text>
            </view>
            <view class="dish-category">
              <text class="category-text">{{ dish.dish && dish.dish.category }}</text>
            </view>
          </view>

          <view class="dish-price">
            <view class="price-info">
              <text class="price-label">计划采购数量-食堂</text>
              <text class="price-value">{{ dish.planned_quantity || '-' }}</text>
            </view>
          </view>
          <view class="dish-price">
            <view class="price-info">
              <text class="price-label">采购备注-食堂</text>
              <text class="price-value">{{ dish.planned_remark || '-' }}</text>
            </view>
          </view>
          <view class="dish-price-input">
            <text class="price-label">实际采购数量</text>
            <view class="price-input">
              <u-number-box input-width="120" :positive-integer="false" step="1" v-model="dish.actual_quantity"></u-number-box>
              <text class="price-unit">{{ dish.dish && dish.dish.unit }}</text>
            </view>
          </view>
          <view class="dish-price-input">
            <text class="price-label">实际采购价格</text>
            <view class="price-input">
              <u-number-box input-width="120" :positive-integer="false" step="1" v-model="dish.actual_price"></u-number-box>
              <text class="price-unit">元</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部统计 -->
    <view class="bottom-stats">
      <view class="stats-info">
        <view class="stats-text">总菜品数：{{ dishList.length }} 个</view>
        <view class="stats-text">已填写采购数量：{{ filledQuantityCount }} 个</view>
        <view class="stats-text">已填写采购价格：{{ filledPriceCount }} 个</view>
      </view>
      <view class="stats-total">
        <text class="total-label">实际采购总价</text>
        <text class="total-value">¥{{ totalPrice }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import api from "../../config/api.js";

export default {
  data() {
    return {
      workorderId: '',
      loading: true,
      searchKeyword: '',
      dishList: [],

      // 采购单信息
      workorderInfo: {},

      // 已存在的菜单项
      existingMenuItems: [],
      dishRatingMap: {}
    }
  },

  computed: {
    // 过滤后的菜品列表
    filteredDishList() {
      if (!this.searchKeyword) {
        return this.dishList;
      }
      return this.dishList.filter(dish => (dish.dish.name && dish.dish.name.includes(this.searchKeyword)) || dish.dish.category && dish.dish.category.includes(this.searchKeyword));
    },

    // 已填写收货数量的菜品数
    filledQuantityCount() {
      return this.dishList.filter(dish =>
          dish.actual_quantity !== null &&
          dish.actual_quantity !== undefined &&
          dish.actual_quantity > 0
      ).length;
    },

    // 已填写采购价格的菜品数
    filledPriceCount() {
      return this.dishList.filter(dish =>
          dish.actual_price !== null &&
          dish.actual_price !== undefined &&
          dish.actual_price > 0
      ).length;
    },

    // 总价
    totalPrice() {
      return this.dishList.reduce((total, dish) => {
        if (dish.actual_quantity && dish.actual_quantity > 0) {
          const price = dish.actual_price || 0
          console.log(price, dish.actual_quantity)
          return total + (price * dish.actual_quantity);
        }
        return total;
      }, 0).toFixed(2);
    }
  },

  onLoad(options) {
    this.$store.dispatch('getUserInfo')
    if (options.id) {
      this.workorderId = options.id;
      this.loadWorkorderInfo();
    }

    this.$api.getDishRatingList().then(res => {
      let dishRatingMap = {}
      // 将不同分类使用map形式
      res.forEach(item => {
        let key = `${item.category}-${item.dish_name}`
        if (!dishRatingMap[key]) {
          dishRatingMap[key] = item.rating_value.split(',')
        }
      })
      this.dishRatingMap = dishRatingMap
      console.log('dishRatingMap',dishRatingMap);

    })
  },

  methods: {
    // 返回上一页
    goBack() {

      uni.switchTab({
                url: '/pages/workorder/workorder'
              })
    },

    // 加载采购单信息
    loadWorkorderInfo() {
      api.getDailyMenu(this.workorderId).then(response => {
        this.workorderInfo = response;
        this.loadDishList();
      }).catch(error => {
        console.error('加载采购单信息失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
    },

    // 加载菜品列表
    async loadDishList() {
      this.loading = true;

      try {
        // 获取菜品列表（基于月度比价项目）
        const params = {
          daily_menu_id: this.workorderInfo.id,
        };

        const dishResponse = await api.getDailyMenuItemList(params);
        this.dishList = (dishResponse || []).map(dish => ({
          ...dish,
          actual_quantity: dish.actual_quantity || dish.planned_quantity || 0
        }));

      } catch (error) {
        console.error('加载菜品列表失败:', error);

      } finally {
        this.loading = false;
      }
    },

    // 搜索输入
    onSearchInput() {
      // 实时搜索逻辑
    },

    // 数量输入
    onQuantityInput(dish, value) {
      // 处理以0开头的输入格式，如000、001等
      if (value === '' || value === null || value === undefined) {
        dish.actual_quantity = 0;
        return;
      }
      console.log(typeof value)
      // 如果是字符串且以0开头，需要特殊处理
      if (typeof value === 'string' && value.startsWith('0') && value.length > 1) {
        // 如果输入的是000、001等格式，转换为对应的数字
        const numValue = parseInt(value);
        if (isNaN(numValue) || numValue <= 0) {
          dish.actual_quantity = 0;
        } else {
          dish.actual_quantity = numValue;
        }
      } else {
        // 正常数字处理
        const numValue = parseFloat(value);
        if (isNaN(numValue) || numValue < 0) {
          dish.actual_quantity = 0;
        } else {
          dish.actual_quantity = numValue;
        }
      }
    },
    // 价格输入
    onPriceInput(dish, value) {
      // 处理以0开头的输入格式，如000、001等
      if (value === '' || value === null || value === undefined) {
        dish.actual_price = 0;
        return;
      }

      // 如果是字符串且以0开头，需要特殊处理
      if (typeof value === 'string' && value.startsWith('0') && value.length > 1) {
        // 如果输入的是000、001等格式，转换为对应的数字
        const numValue = parseFloat(value);
        if (isNaN(numValue) || numValue < 0) {
          dish.actual_price = 0;
        } else {
          dish.actual_price = numValue;
        }
      } else {
        // 正常数字处理
        const numValue = parseFloat(value);
        if (isNaN(numValue) || numValue < 0) {
          dish.actual_price = 0;
        } else {
          dish.actual_price = numValue;
        }
      }
    },

    // 选择品质评价
    selectQuality(dish, rating) {
      dish.quality_rating = rating;
    },
    save() {
      this.saveDishes(false)
    },
    submit() {
      // 验证所有有数量的菜品都有价格
      const dishesWithoutPrice = this.dishList.filter(dish =>
          !dish.actual_price || dish.actual_price <= 0
      );

      if (dishesWithoutPrice.length > 0) {
        uni.showToast({
          title: '请为所有菜品设置有效的采购价格',
          icon: 'none'
        });
        return;
      }
      // const dishesWithoutQuantity = this.dishList.filter(dish =>
      //     !dish.actual_quantity || dish.actual_quantity <= 0
      // );
      //
      // if (dishesWithoutQuantity.length > 0) {
      //   uni.showToast({
      //     title: '请为所有菜品设置有效的采购数量',
      //     icon: 'none'
      //   });
      //   return;
      // }
      uni.showModal({
        title: '提示',
        content: '确认提交吗？',
        success: (res) => {
          if (res.confirm) {
            this.saveDishes(true)
          }
        }
      })
    },
    // 保存菜品选择
    async saveDishes(isSubmit = false) {

      try {
        // 只保存有采购数量的菜品
        // const dishesToSave = this.dishList.filter(dish =>
        //     dish.actual_quantity && dish.actual_quantity > 0 &&
        //     dish.actual_price && dish.actual_price > 0
        // );
        // 批量更新菜品明细
        const submitData = this.dishList.map(dish => ({
          daily_menu_id: this.workorderId,
          id: dish.id,
          actual_quantity: dish.actual_quantity,
          actual_price: dish.actual_price
        }));

        const updateData = this.dishList.map(dish => ({
          id: dish.id,
          actual_quantity: dish.actual_quantity,
          actual_price: dish.actual_price
        }));

        await api[isSubmit ? 'batchConfirmBuy' : 'batchUpdateDailyMenuItem'](isSubmit ? submitData : updateData);

        uni.showToast({
          title: isSubmit ? '提交成功' : '保存成功',
          icon: 'success'
        });
        if (isSubmit) {
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        }

      } catch (error) {
        console.error('确认收货失败:', error);
      }
    }
  }
}
</script>

<style lang="scss">
.dishes-container {
  background-color: #f5f5f5;
  padding-bottom: 180rpx;
  padding-top: 90rpx;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

// 顶部导航
.header {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  width: 100%;
  z-index: 2;
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .back-btn {
      .back-text {
        font-size: 32rpx;
        color: #666;
      }
    }

    .title {
      .title-text {
        font-size: 36rpx;
        color: #333;
        font-weight: 600;
      }
    }

    .save-btn {
      .save-text {
        font-size: 32rpx;
        color: #FFC300;
        font-weight: 500;
      }
    }
  }
}

// 搜索栏
.search-section {
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;

  .search-box {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    border-radius: 24rpx;
    padding: 16rpx 24rpx;
    gap: 12rpx;

    .search-icon {
      width: 32rpx;
      height: 32rpx;
    }

    .search-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
  }
}

// 菜品列表
.dish-list {
  height: 100%;
}

// 加载状态
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;

  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  padding: 0 32rpx;

  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
    opacity: 0.6;
  }

  .empty-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: #ccc;
  }
}

.dish-list-container {
  padding: 0 32rpx;
}

.dish-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;

  .dish-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .dish-name {
      .name-text {
        font-size: 32rpx;
        color: #333;
        font-weight: 600;
      }
    }

    .dish-category {
      .category-text {
        font-size: 24rpx;
        color: #666;
        background-color: #e8e8e8;
        padding: 8rpx 16rpx;
        border-radius: 8rpx;
      }
    }
  }

  .dish-price {
    margin-bottom: 24rpx;

    .price-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .price-label {
        font-size: 26rpx;
        color: #666;
      }

      .price-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;

        &.quoted {
          color: #FF6B35;
          font-weight: 600;
        }
      }
    }
  }

  .dish-quantity {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .quantity-label {
      font-size: 26rpx;
      color: #666;
    }

    .quantity-input {
      display: flex;
      align-items: center;
      border: 1rpx solid #e8e8e8;
      border-radius: 8rpx;
      overflow: hidden;

      .quantity-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f5f5f5;

        .btn-text {
          font-size: 32rpx;
          color: #333;
          font-weight: 600;
        }
      }

      .quantity-field {
        width: 120rpx;
        height: 60rpx;
        text-align: center;
        font-size: 28rpx;
        color: #333;
        border: none;
        background-color: #fff;
      }
    }

    .unit-text {
      font-size: 26rpx;
      color: #666;
    }
  }

  .dish-price-input {
    margin-bottom: 24rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .price-label {
      display: block;
      font-size: 26rpx;
      color: #666;
    }

    .price-input {
      position: relative;
      display: flex;
      align-items: center;
      flex-grow: 1;
      justify-content: flex-end;

      .price-field {
        flex: 1;
        margin-right: 60rpx;
      }

      .price-unit {
        font-size: 28rpx;
        color: #666;
        z-index: 1;
        margin-left: 12rpx;
      }
    }
  }

  .dish-quality {
    margin-bottom: 24rpx;

    .quality-label {
      display: block;
      font-size: 26rpx;
      color: #666;
      margin-bottom: 16rpx;
    }

    .quality-tags {
      display: flex;
      gap: 16rpx;

      .quality-tag {
        padding: 12rpx 24rpx;
        border: 1rpx solid #e8e8e8;
        border-radius: 8rpx;
        background-color: #fff;

        .tag-text {
          font-size: 26rpx;
          color: #666;
        }

        &.active {
          border-color: #FFC300;
          background-color: #FFF8E1;

          .tag-text {
            color: #FFC300;
            font-weight: 500;
          }
        }
      }
    }
  }

  .dish-remark {
    .remark-label {
      display: block;
      font-size: 26rpx;
      color: #666;
      margin-bottom: 16rpx;
    }

    .remark-input {
      position: relative;

      .remark-field {
        width: 100%;
        font-size: 28rpx;
        color: #333;
        line-height: 1.5;
        height: 120rpx;
        padding: 16rpx;
        border: 1rpx solid #e8e8e8;
        border-radius: 8rpx;
        background-color: #fff;
      }

      .char-count {
        text-align: right;
        margin-top: 8rpx;

        .count-text {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}

// 底部统计
.bottom-stats {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .stats-info {
    display: flex;
    flex-direction: column;
    gap: 8rpx;

    .stats-text {
      font-size: 20rpx;
      color: #666;
    }
  }

  .stats-total {
    display: flex;
    align-items: center;
    gap: 12rpx;

    .total-label {
      font-size: 28rpx;
      color: #666;
    }

    .total-value {
      font-size: 36rpx;
      color: #FF6B35;
      font-weight: 600;
    }
  }
}
</style>
